﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

using NETCONLib;

namespace HAOest.Net
{
    /// <summary>
    /// 网卡操作
    /// </summary>
    public class NetworkManager
    {
        /// <summary>
        /// 支持的网卡类型
        /// </summary>
        private static List<NetworkInterfaceType> SupportedInterfaceType = new List<NetworkInterfaceType> { NetworkInterfaceType.Ethernet, NetworkInterfaceType.Wireless80211 };

        /// <summary>
        /// 获取使用中的网络适配器（仅限支持的网卡类型）
        /// </summary>
        /// <returns></returns>
        public static List<NetworkInterface> GetEnabledAdapters()
        {
            List<NetworkInterface> enabledAdapters = new List<NetworkInterface>();
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本机所有网卡对象
            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up && SupportedInterfaceType.Contains(adapter.NetworkInterfaceType))
                    enabledAdapters.Add(adapter);
            }
            return enabledAdapters;
        }

        /// <summary>
        /// 通过适配器描述的关键词获取该适配器的IP地址
        /// </summary>
        /// <returns></returns>
        public static IPAddress GetIPAddressByKeyword(string keyword)
        {
            IPAddress ipAddress = null;
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本机所有网卡对象
            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.Description.Contains(keyword))
                {
                    IPInterfaceProperties ipProperties = adapter.GetIPProperties();//获取IP配置
                    UnicastIPAddressInformationCollection ipCollection = ipProperties.UnicastAddresses;//获取单播地址集
                    foreach (UnicastIPAddressInformation ip in ipCollection)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)//IPv4地址
                            ipAddress = ip.Address;
                    }
                }
            }
            return ipAddress;
        }

        /// <summary>
        /// 开启网络共享
        /// </summary>
        /// <param name="connectionShareForm">网络提供者网卡的名字</param>
        /// <param name="connectionShareTo">网络接受者网卡的名字</param>
        public static void EnableInternetConnectionSharing(string connectionShareForm, string connectionShareTo)
        {
            var manager = new NetSharingManager();
            var connections = manager.EnumEveryConnection;
            foreach (INetConnection c in connections)
            {
                var props = manager.NetConnectionProps[c];
                var sharingCfg = manager.INetSharingConfigurationForINetConnection[c];

                if (props.Name == connectionShareForm)
                {
                    sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PUBLIC);
                }
                else if (props.Name == connectionShareTo)
                {
                    sharingCfg.EnableSharing(tagSHARINGCONNECTIONTYPE.ICSSHARINGTYPE_PRIVATE);
                }
            }
        }

        /// <summary>
        /// 开启承载网络
        /// </summary>
        /// <param name="ssid">承载网络名</param>
        /// <param name="key">承载网络密码</param>
        /// <returns></returns>
        public static string OpenHostedNetwork(string ssid, string key)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";           //设定程序名
            p.StartInfo.UseShellExecute = false;        //关闭Shell的使用
            p.StartInfo.RedirectStandardInput = true;   //重定向标准输入
            p.StartInfo.RedirectStandardOutput = true;  //重定向标准输出
            p.StartInfo.RedirectStandardError = true;   //重定向错误输出
            p.StartInfo.CreateNoWindow = true;          //设置不显示窗口
            p.Start();
            p.StandardInput.WriteLine("@ECHO ON");      //输入要执行的命令
            p.StandardInput.WriteLine("netsh wlan set hostednetwork mode=allow");
            p.StandardInput.WriteLine("netsh wlan set hostednetwork ssid=" + ssid);
            p.StandardInput.WriteLine("netsh wlan set hostednetwork key=" + key);
            p.StandardInput.WriteLine("netsh wlan start hostednetwork");
            p.StandardInput.WriteLine("exit");
            string output = p.StandardOutput.ReadToEnd();        //从输出流获取命令执行结果
            p.Close();
            return output;
        }

        /// <summary>
        /// 关闭承载网络
        /// </summary>
        /// <returns></returns>
        public static string CloseHostedNetwork()
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";           //设定程序名
            p.StartInfo.UseShellExecute = false;        //关闭Shell的使用
            p.StartInfo.RedirectStandardInput = true;   //重定向标准输入
            p.StartInfo.RedirectStandardOutput = true;  //重定向标准输出
            p.StartInfo.RedirectStandardError = true;   //重定向错误输出
            p.StartInfo.CreateNoWindow = true;          //设置不显示窗口
            p.Start();
            p.StandardInput.WriteLine("@ECHO ON");      //输入要执行的命令
            p.StandardInput.WriteLine("netsh wlan stop hostednetwork");
            p.StandardInput.WriteLine("exit");
            string output = p.StandardOutput.ReadToEnd();        //从输出流获取命令执行结果
            p.Close();
            return output;
        }

    }
}
